/**
 * 管理控制器
 * 提供管理相关功能，包括系统监控
 */

const BaseController = require('./base_controller.js');
const dataMonitor = require('../monitoring/data_monitor');

class AdminController extends BaseController {

  /** 构造函数 */
  constructor() {
    super();
  }

  /**
   * 获取数据监控仪表盘数据
   */
  async getMonitoringDashboard() {
    // 权限检查
    await this.isAdmin();
    
    try {
      // 获取数据库引用
      const cloud = this.cloud;
      const db = cloud.database();
      const _ = db.command;
      const $ = _.aggregate;
      
      // 获取当前时间
      const now = Math.floor(Date.now() / 1000);
      const oneDayAgo = now - 86400; // 24小时前
      
      // 获取操作日志统计
      const logStats = await db.collection('plm_data_operations_log')
        .aggregate()
        .match({
          timestamp: _.gte(oneDayAgo)
        })
        .group({
          _id: '$operation',
          count: $.sum(1),
          avgDuration: $.avg('$metadata.duration'),
          errorCount: $.sum($.cond({
            if: '$metadata.success',
            then: 0,
            else: 1
          }))
        })
        .end();
      
      // 获取最近错误日志
      const recentErrors = await db.collection('plm_data_operations_log')
        .where({
          timestamp: _.gte(oneDayAgo),
          'metadata.success': false
        })
        .orderBy('timestamp', 'desc')
        .limit(10)
        .get();
      
      // 获取性能监控数据
      const performanceData = await db.collection('plm_data_operations_log')
        .where({
          timestamp: _.gte(oneDayAgo),
          'metadata.isSlowOperation': true
        })
        .orderBy('metadata.duration', 'desc')
        .limit(10)
        .get();
      
      // 获取最近的一致性检查结果
      const latestConsistencyCheck = await db.collection('plm_data_operations_log')
        .where({
          operation: 'consistency_check'
        })
        .orderBy('timestamp', 'desc')
        .limit(1)
        .get();
      
      // 获取告警统计
      const alertStats = await db.collection('plm_system_alerts')
        .where({
          timestamp: _.gte(oneDayAgo)
        })
        .count();
      
      // 汇总数据
      const dashboardData = {
        timestamp: now,
        operationStats: logStats.list,
        recentErrors: recentErrors.data,
        performanceIssues: performanceData.data,
        consistencyCheckResult: latestConsistencyCheck.data[0] || null,
        alertCount: alertStats.total,
        systemHealth: this._calculateSystemHealth(
          logStats.list, 
          recentErrors.data.length, 
          latestConsistencyCheck.data[0]
        )
      };
      
      return this.success(dashboardData);
    } catch (error) {
      console.error('[管理控制器] 获取监控仪表盘数据失败:', error);
      return this.fail('获取监控数据失败:' + error.message);
    }
  }

  /**
   * 计算系统健康状态
   * @private
   */
  _calculateSystemHealth(operationStats, errorCount, consistencyCheck) {
    // 初始健康评分为100
    let healthScore = 100;
    
    // 根据错误数量扣分
    if (errorCount > 0) {
      healthScore -= Math.min(50, errorCount * 5); // 每个错误扣5分，最多扣50分
    }
    
    // 根据操作统计扣分
    if (operationStats && operationStats.length > 0) {
      // 计算总体错误率
      const totalOperations = operationStats.reduce((sum, stat) => sum + stat.count, 0);
      const totalErrors = operationStats.reduce((sum, stat) => sum + stat.errorCount, 0);
      
      if (totalOperations > 0) {
        const errorRate = totalErrors / totalOperations;
        if (errorRate > 0.01) { // 错误率>1%
          healthScore -= Math.min(30, errorRate * 1000); // 根据错误率扣分，最多扣30分
        }
      }
    }
    
    // 根据一致性检查结果扣分
    if (consistencyCheck && consistencyCheck.metadata) {
      const { total, failed } = consistencyCheck.metadata;
      if (total > 0 && failed > 0) {
        const failRate = failed / total;
        healthScore -= Math.min(20, failRate * 100); // 根据失败率扣分，最多扣20分
      }
    }
    
    // 返回健康状态
    if (healthScore >= 90) {
      return { status: 'excellent', score: healthScore, description: '系统运行良好' };
    } else if (healthScore >= 70) {
      return { status: 'good', score: healthScore, description: '系统状态正常，存在少量问题' };
    } else if (healthScore >= 50) {
      return { status: 'fair', score: healthScore, description: '系统运行不稳定，需要关注' };
    } else {
      return { status: 'poor', score: healthScore, description: '系统存在严重问题，需要立即处理' };
    }
  }

  /**
   * 手动触发数据一致性检查
   */
  async triggerConsistencyCheck() {
    // 权限检查
    await this.isAdmin();
    
    try {
      // 获取数据库
      const cloud = this.cloud;
      const db = cloud.database();
      
      // 获取项目数据
      const result = await db.collection('plm_research_project')
        .limit(1000) // 一次最多检查1000条记录
        .get();
      
      // 进行一致性检查
      const checkResult = await dataMonitor.checkDataConsistency(result.data);
      
      return this.success({
        timestamp: Math.floor(Date.now() / 1000),
        total: checkResult.total,
        passed: checkResult.passed,
        failed: checkResult.failed,
        warnings: checkResult.warnings,
        issues: checkResult.issues.slice(0, 20) // 只返回前20个问题
      });
    } catch (error) {
      console.error('[管理控制器] 触发一致性检查失败:', error);
      return this.fail('一致性检查失败:' + error.message);
    }
  }
  
  /**
   * 获取最近系统告警
   */
  async getRecentAlerts() {
    // 权限检查
    await this.isAdmin();
    
    try {
      // 获取数据库引用
      const cloud = this.cloud;
      const db = cloud.database();
      const _ = db.command;
      
      // 获取最近7天的告警
      const now = Math.floor(Date.now() / 1000);
      const sevenDaysAgo = now - 7 * 86400; // 7天前
      
      const alerts = await db.collection('plm_system_alerts')
        .where({
          timestamp: _.gte(sevenDaysAgo)
        })
        .orderBy('timestamp', 'desc')
        .limit(50)
        .get();
      
      return this.success({
        timestamp: now,
        alerts: alerts.data
      });
    } catch (error) {
      console.error('[管理控制器] 获取系统告警失败:', error);
      return this.fail('获取系统告警失败:' + error.message);
    }
  }
  
  /**
   * 清理历史监控数据
   */
  async cleanupMonitoringData() {
    // 权限检查
    await this.isAdmin();
    
    // 获取参数
    let { days = 30 } = this.getParams();
    
    // 确保天数在合理范围
    days = Math.max(7, Math.min(365, parseInt(days)));
    
    try {
      // 获取数据库引用
      const cloud = this.cloud;
      const db = cloud.database();
      const _ = db.command;
      
      // 计算截止时间
      const now = Math.floor(Date.now() / 1000);
      const cutoffTime = now - days * 86400; // X天前
      
      // 删除旧的操作日志
      const deleteLogsResult = await db.collection('plm_data_operations_log')
        .where({
          timestamp: _.lt(cutoffTime)
        })
        .remove();
      
      // 删除旧的告警（保留最近90天）
      const alertCutoffTime = now - 90 * 86400; // 90天前
      const deleteAlertsResult = await db.collection('plm_system_alerts')
        .where({
          timestamp: _.lt(alertCutoffTime)
        })
        .remove();
      
      return this.success({
        timestamp: now,
        deletedLogs: deleteLogsResult.deleted || 0,
        deletedAlerts: deleteAlertsResult.deleted || 0,
        days: days
      });
    } catch (error) {
      console.error('[管理控制器] 清理监控数据失败:', error);
      return this.fail('清理监控数据失败:' + error.message);
    }
  }
}

module.exports = AdminController; 